package com.example.filerwdemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hp on 2018/6/22.
 */

public class MyDBHelper extends SQLiteOpenHelper {
    private  Context ctx;

    private final String CREATE_TABLE = "create table userinfo("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name varchar(20),"
            +"pwd varchar(20))";





    public MyDBHelper(Context context) {
        super(context,"user.db",null,1);
        this.ctx=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
        Toast.makeText(ctx, "Creat OK", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
    public void insert(String name,String pwd)
    {
        SQLiteDatabase db=getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",name);
        values.put("pwd",pwd);
        db.insert("userInfo",null,values);
        db.close();
    }
    public List<Map<String,String>> query(){
        SQLiteDatabase db = getReadableDatabase();
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        /*columns:查询的列名
        * selection：where约束条件
        * selectionArgs: where中的占位符提供具体的值
        * groupby：group by 子句
        * having：having子句
        * orderBy：order by子句*/
        Cursor cursor = db.query("userInfo",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            do{
                Map<String,String> rec = new HashMap<String,String>();
                rec.put("name",cursor.getString(cursor.getColumnIndex("name")));
                rec.put("pwd",cursor.getString(cursor.getColumnIndex("pwd")));
                list.add(rec);
            }while(cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return  list;
    }

}
